<template>
  <div class="nm-popup">
    <!-- 显示框 -->
    <el-input
      v-model="displayValue"
      readonly
      :placeholder="nm.columnComment"
      @click="showPopup = true"
    >
      <template #append>
        <el-button icon="Search" @click="showPopup = true" />
      </template>
    </el-input>

    <!-- 弹出选择窗口 -->
    <el-dialog
      v-model="showPopup"
      :title="`选择${nm.columnComment}`"
      width="60%"
      append-to-body
    >
      <!-- 搜索栏 -->
      <el-form :inline="true" class="search-form">
        <el-form-item label="关键词">
          <el-input
            v-model="searchKey"
            placeholder="输入关键词搜索"
            @keyup.enter="loadData"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadData">搜索</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        :data="tableData"
        highlight-current-row
        @row-click="handleRowClick"
      >
        <el-table-column
          v-for="col in columns"
          :key="col.prop"
          :prop="col.prop"
          :label="col.label"
        />

        <el-table-column width="55">
          <template #default="{row}">
            <el-radio v-model="selectedId" :label="row[keyField]">&nbsp;</el-radio>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        layout="total, prev, pager, next"
        @current-change="loadData"
      />

      <!-- 添加弹窗底部按钮 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, onMounted } from 'vue'
import { listOnlineData, getPopupDetail } from '@/api/online'
import { ElMessage } from 'element-plus'

defineOptions({ name: 'NmPopup' })

const props = defineProps({
  nm: {
    type: Object,
    required: true
  },
  value: [String, Number] // 绑定的主键值
})

const emit = defineEmits(['update:value', 'commonComponent'])

// 组件状态
const showPopup = ref(false)
const displayValue = ref('')
const tableData = ref([])
const selectedId = ref(null)
const searchKey = ref('')
const tempSelectedRow = ref<any>(null) // 新增临时存储选中行

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 获取配置字段
const keyField = props.nm.keyField || 'id'
const displayField = props.nm.displayField || 'name'

// 动态columns配置
const columns = computed(() => {
  try {
    const fieldsConfig = JSON.parse(
      props.nm.dictFields.replace(/'/g, '"').replace(/“/g, '"').replace(/”/g, '"')
    )
    return Object.entries(fieldsConfig).map(([prop, label]) => ({
      prop,
      label: label as string
    }))
  } catch (e) {
    console.error('dictFields解析失败:', props.nm.dictFields)
    return [{ prop: 'code', label: '编码' }, { prop: 'name', label: '名称' }]
  }
})

const queryParams = reactive<any>({
    pageNum: 1,
    pageSize: 10,
    params: {}
})

// 加载数据
const loadData = async () => {
  try {
    const res = await listOnlineData(props.nm.tableId, props.nm.dictType,queryParams)
    tableData.value = res.rows
    total.value = res.total
  } catch (error) {
    console.error('加载弹出数据失败:', error)
    ElMessage.error('数据加载失败')
  }
}

// 行点击处理
const handleRowClick = (row: any) => {
  selectedId.value = row[keyField]
  tempSelectedRow.value = row  // 存储选中行数据
}

// 确认选择处理逻辑
const handleConfirm = () => {
  if (!tempSelectedRow.value) {
    ElMessage.warning('请先选择一条记录')
    return
  }

  // 安全解析配置
  const dictFields = safeParseJSON(props.nm.dictFields) || {}
  const mapping = safeParseJSON(props.nm.mapping) || {}

  // 构建返回数据（严格字段映射）
  const returnData = {
    id: selectedId.value,
    display: displayValue.value,
    dictFields: dictFields,
    mapping: mapping,
    commonDataInfo: Object.keys(dictFields).reduce((acc, sourceField) => {
      const targetField = mapping[sourceField] || sourceField
      console.log("targetField",targetField)

      acc[targetField] = convertValueType(
        tempSelectedRow.value[sourceField],
        props.nm.javaType // 携带字段类型信息
      )
      console.log("acc[targetField]",acc[targetField])
      return acc
    }, {} as Record<string, any>)
  }

  // 添加主键映射
  //returnData.commonDataInfo[props.nm.columnName] = selectedId.value
  console.log("handleConfirm returnData",returnData)
  emit('update:value', selectedId.value)
  emit('commonComponent', returnData)
  showPopup.value = false
}

// 添加通用JSON解析方法
const safeParseJSON = (str: any) => {
  if (typeof str !== 'string') return str
  try {
    return JSON.parse(
      str
        .replace(/[“”]/g, '"')
        .replace(/'/g, '"')
        .replace(/\\/g, '\\\\')
    )
  } catch (e) {
    console.error('JSON解析失败，原始字符串:', str)
    return {}
  }
}


// 类型转换辅助方法
const convertValueType = (value: any, javaType: string) => {
  if (value === null || value === undefined) return null

  switch(javaType) {
    case 'Long':
    case 'Integer':
      return Number(value) || 0
    case 'BigDecimal':
    case 'Double':
      return parseFloat(value) || 0
    default:
      return String(value)
  }
}

// 取消选择
const handleCancel = () => {
  // 清空临时选择
  selectedId.value = null
  tempSelectedRow.value = null
  showPopup.value = false
}

// 初始化加载显示值
const loadDisplayValue = async () => {
  if (!props.value) {
    displayValue.value = ''
    return
  }

  // 根据配置决定显示方式
  if (props.nm.showDisplay) {
    try {
      const res = await getPopupDetail(props.nm.tableId, props.nm.dictType, props.value)
      displayValue.value = res.data[displayField]
    } catch (error) {
      console.error('加载显示值失败:', error)
      ElMessage.error('显示值加载失败')
    }
  } else {
    displayValue.value = props.value.toString()
  }
  selectedId.value = props.value
}

// 监听value变化（用于编辑时回显）
watch(() => props.value, (newVal) => {
  if (newVal) {
    loadDisplayValue()
  } else {
    displayValue.value = ''
  }
})

// 初始化
onMounted(() => {
  if (props.value) {
    loadDisplayValue()
  }
  loadData()
})
</script>

<style scoped>
.nm-popup :deep(.el-dialog__body) {
  padding: 10px 20px;
}
.search-form {
  margin-bottom: 15px;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
